<template>
  <van-popup v-model="show" :style="{ width: '100%', height: '100%' }">
    <div class="CouponGrant wb flc" :style="{ paddingTop: `${45 + statusBarHeight}px` }">
      <NavBar 
        :navBarStyle="{
          backgroundColor: navBarBg,
          height: `${45 + statusBarHeight}px`,
          paddingTop: `${statusBarHeight}px`,
        }"
        pageName="发放优惠券"
        @onLeftClick="leftBack" 
      >
      </NavBar>
      <div class="fls wb grant_header plr_16">
        <div class="couponItem mb10">
          <div class="grant_coupon_tag package_bg" v-if="couponInfo.benefitBatchType == 20">权益包</div>
          <div class="grant_coupon_tag grant_coupon_bg" v-if="couponInfo.benefitBatchType == 10 && couponInfo.couponType == 10">免单券</div>
          <div class="grant_coupon_tag grant_coupon_bg" v-if="couponInfo.benefitBatchType == 10 && couponInfo.couponType == 20">折扣券</div>
          <div class="grant_coupon_tag grant_coupon_bg" v-if="couponInfo.benefitBatchType == 10 && couponInfo.couponType == 30">代金券</div>
          <!-- 优惠券 -->
          <div class="fl vc grant_coupon_header" v-if="couponInfo.benefitBatchType == 10">
            <div class="fl1">
              <div class="grant_coupon_title">{{ couponInfo.title }}</div>
              <p class="grant_coupon_time" v-if="couponInfo.benefitBatchType == 10 && couponInfo.invalidType == 10">{{ couponInfo.invalidTime ? timeStampToTime(couponInfo.invalidTime, 'Y-m-d H:i') : '-' }} 到期</p>
              <p class="grant_coupon_time" v-if="couponInfo.benefitBatchType == 10 && couponInfo.invalidType == 20">领取后{{ couponInfo.validDays }}天失效</p>
              <div class="fl vc dx_12 mt5">
                <p class="color_A9 mr10 lh_12">本次发放数量/可发放数量</p>
                <p class="color_A9 lh_12">{{ mathUtil.numberRide(grantNum, checkList.length) }}/{{ totalNum === 0 ? '∞' : usable }}</p>
              </div>
            </div>
            <div class="flc vend fls pdl_10">
              <div class="color_red dx_30 ct" v-if="couponInfo.couponType == 10">免单</div>
              <div class="fl vend" v-if="couponInfo.couponType == 20">
                <span class="color_red dx_32 ct">{{ couponInfo.discountAmount / 10 }}</span>
                <span class="color_red dx_14 ct">折</span>
              </div>
              <div class="fl vend" v-if="couponInfo.couponType == 30">
                <span class="color_red dx_14 ct">￥</span>
                <span class="color_red dx_32 ct">{{ formatPriceFloat(couponInfo.discountAmount, 'int') }}</span>
                <span class="color_red dx_20 ct">{{ formatPriceFloat(couponInfo.discountAmount, 'float') }}</span>
              </div>
              <span class="color_c2 dx_11 mt_6">无门槛</span>
            </div>
          </div>
          <!-- 权益包 -->
          <div class="fl vstart bt grant_coupon_header" v-if="couponInfo.benefitBatchType == 20">
              <div class="fl vc">
                <img class="studio_icon fls" src="@/assets/images/studio_icon.png">
                <div class="fl1">
                    <div class="grant_coupon_title">{{ couponInfo.title }}</div>
                    <div class="fl vc dx_12 mt5">
                      <p class="color_A9 mr10 lh_12">本次发放数量/可发放数量：</p>
                      <p class="color_A9 mr lh_12">{{ mathUtil.numberRide(grantNum, checkList.length) }} / ∞</p>
                    </div>
                </div>
              </div>
          </div>
        </div>
        <div class="bkra8 bg_fff pad_12 flvcbt mb10" v-if="couponInfo.benefitBatchType == 10">
          <div class="fl vc">
            <img src="@/assets/images/icon_power.png" class="img20 mr5" />
            <span class="ct dx_15 color_333">每家店铺发放</span>
          </div>
          <van-stepper v-model="grantNum" integer @change="changeNum" />
        </div>
        <div class="bkra_tlr_8 bg_fff pad_12 flvcbt bkb_f3">
          <div class="fl vc">
            <img src="@/assets/images/icon_power.png" class="img20 mr5" />
            <span class="ct dx_15 color_333">选择店铺</span>
          </div>
          <div class="wb60">
            <van-field
              @input="resetSearch"
              v-model.trim="queryParams.storeName"
              left-icon="search"
              placeholder="输入要查询的店铺"
            />
          </div>
        </div>
      </div>
      <div class="hb flau plr_16 grant_content" ref="grantScrollRef">
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <van-checkbox-group @change="handleCheckedChange" v-model="checkList">
            <div class="wb bkb_f3 fl vc" v-for="(item) in storeList" :key="item.storeId">
              <div class="wb bg_fff plr_12">
                <van-checkbox :name="item.storeId" icon-size="20px" checked-color="#D1FB71">
                  <div class="fl vc ptb_10 wb">
                    <div class="fls">
                      <van-image
                        width="48px"
                        height="48px"
                        radius="5px"
                        lazy-load
                        fit="cover"
                        v-if="item.storeImg"
                        :src="item.storeImg"
                      />
                      <img src="@/assets/images/icon_store.png" class="img48 bkra5" v-else />
                    </div>
                    <div class="pdl_12 fl1" style="overflow: hidden">
                      <p class="ct dx_15 mr5 wb">{{ fnOmit(item.shopName, 10) }}</p>
                      <div class="fl wb vc mt5">
                        <img src="@/assets/images/icon_location.png" class="img16 mr5 fls" />
                        <p class="dx_13 color_8c fl1 omit">{{ item.address }}</p>
                      </div>
                    </div>
                  </div>
                </van-checkbox>
              </div>
            </div>
          </van-checkbox-group>
        </van-list>
      </div>
      <div class="fls pad_16 bg_fff mt10 grant_footer">
        <div v-if="checkList.length > 0" class="mb10 dx_14 color_999">已选{{ checkList.length }}家店铺,每家店铺发放{{grantNum}}</div>
        <div class="fl vc">
          <div class="fl1">
            <van-checkbox @click.stop="handleClickAll" v-model="checkAll" icon-size="20px" checked-color="#D1FB71">全选</van-checkbox>
          </div>
          <p class="grant_btn flvcc fls" @click="clickGive">发放优惠券</p>
        </div>
      </div>
    </div>
  </van-popup>
</template>

<script>
import NavBar from '@/components/NavBar/NavBar.vue'
import { Overlay, Popup, List, Checkbox, CheckboxGroup, Field, Stepper, Dialog } from 'vant';
import { Toast } from 'vant';
import { navOtherHeight } from '@/config/config'
import { formatterStatus, fnOmit, formatPriceFloat, timeStampToTime } from '@/utils/util'
import { getStoreList, issueCouponToStoreList, addBenefitPackageList, selectCouponPage } from '@/api/store.js'
import { getApplyScriptList } from '@/api/script.js'
import mathUtil from '@/utils/mathUtil'

export default {
  props: {
    navigationHeight: {
      type: [String, Number],
      default: 0,
    },
    statusBarHeight: {
      type: [String, Number],
      default: 0,
    },
  },
  components: {
    [Overlay.name]: Overlay,
    [Popup.name]: Popup,
    [List.name]: List,
    [Checkbox.name]: Checkbox,
    [CheckboxGroup.name]: CheckboxGroup,
    [Dialog.Component.name]: Dialog.Component,
    [Field.name]: Field,
    [Stepper.name]: Stepper,
    NavBar
  },

  data() {
    return {
      mathUtil,
      formatterStatus,
      formatPriceFloat,
      timeStampToTime,
      fnOmit,
      navBarBg: '#F6F6F6',
      navOtherHeight,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storeName: '',
        authStoreFlag: true
      },
      showSearch: false,
      loading: true,
      finished: false,
      storeList: [],
      scriptList: [],
      batchList: [],

      show: false,
      couponInfo: {},
      totalNum: 0,
      usable: 0,

      checkAll: false,
      checkList: [],
      grantNum: 1
    };
  },

  created() {

  },

  methods: {
    onLoad() {
      console.log('到底')
      this.queryParams.pageNum += 1
      this.getStoreList()
    },
    resetSearch() {
      this.queryParams.pageNum = 1
      this.getStoreList()
    },

    initData (item) {
      this.show = true
      this.couponInfo = item
      if (this.couponInfo.benefitBatchType == 10) {
        const usedNum = this.couponInfo.grantNum || 0
        this.totalNum = this.couponInfo.totalNum || 0
        this.usable = this.couponInfo.totalNum === 0 ? 0 : this.totalNum - usedNum
        if (this.totalNum > 0 && this.grantNum > this.usable) {
          this.grantNum = this.usable
        }
      } else {
        this.grantNum = 1
      }
      this.queryParams.storeName = ''
      this.checkAll = false
      this.checkList = []
      setTimeout(() => {
        this.$refs.grantScrollRef.scrollTop= 0
        this.queryParams.pageNum = 1
        this.getStoreList()
        // this.getBatchList()
      }, 500)
    },

    leftBack () {
      this.show = false
    },

    getAPPNavHeight () {
      console.log('--appNavigation--', window)
      if (window.androidJSBridge) {
        const result = JSON.parse(window.androidJSBridge.appNavigation())
        this.navigationHeight = result.navigationHeight
        this.statusBarHeight = result.statusBarHeight
        console.log('android1', result)
      } else if (window.webkit) {
        console.log('ios-appNavigation')
        window.appNavigation = this.onAppNavigation
        window.webkit.messageHandlers.appNavigation.postMessage({})
      }
    },

    onAppNavigation (result) {
      console.log('ios--appNavigation', result)
      this.navigationHeight = Number(result.navigationHeight)
      this.statusBarHeight = Number(result.statusBarHeight)
    },

    // 多选店铺
    // handleCheckAllChange (val) {
    //   console.log(val)
    //   if (!val && this.checkList.length < this.storeList.length) {
    //     return
    //   } else {
        
    //   }
    // },
    // 点击全选
    handleClickAll() {
      console.log('click:', this.checkAll)
      const list = this.storeList.map(item => item.storeId)
      if (this.checkAll) {
        if (this.queryParams.storeName) {
          this.checkList = Array.from(new Set([...this.checkList, ...list]))
        } else {
          this.checkList = list
        }
      } else {
        if (this.queryParams.storeName) {
          this.checkList = this.checkList.filter(item => !list.includes(item))
        } else {
          this.checkList = []
        }
      }
      // this.checkList = val ? this.storeList.map(item => item.storeId) : []
      this.changeNum()
    },
    handleCheckedChange () {
      const list = this.storeList.map(item => item.storeId)
      // console.log('list:', list, this.checkList)
      const checkedCount = this.checkList.filter(item => list.includes(item)).length
      this.checkAll = checkedCount === this.storeList.length
      this.changeNum()
    },

    // 变更发放数量
    changeNum() {
      if (this.grantNum === 0) {
        setTimeout(() => {
          this.grantNum = 1
        }, 300)
      }
      if (this.totalNum > 0 && mathUtil.numberRide(this.grantNum, this.checkList.length) > this.usable) {
        Toast(`该优惠批次可发数量为${this.usable}张`)
        setTimeout(() => {
          this.grantNum = this.usable < this.checkList.length ? 1 : parseInt(mathUtil.numberExcept(this.usable, this.checkList.length))
        }, 500)
      }
    },
    // 切换优惠
    onConfirm(obj) {
      this.show = false
      console.log(obj)
      this.couponInfo = obj
      if (this.couponInfo.benefitBatchType == 10) {
        const usedNum = this.couponInfo.grantNum || 0
        this.totalNum = this.couponInfo.totalNum || 0
        this.usable = this.couponInfo.totalNum === 0 ? 0 : this.totalNum - usedNum
        if (this.totalNum > 0 && this.grantNum > this.usable) {
          this.grantNum = this.usable
        }
      } else {
        this.grantNum = ''
      }
    },

    // 发放
    clickGive() {
      if (!this.couponInfo.benefitBatchId) {
        Toast('请选择优惠')
        return false
      }
      if (this.couponInfo.benefitBatchType == 10 && !this.grantNum) {
        Toast('请输入发放数量')
        return false
      }
      if (this.checkList.length === 0) {
        Toast('请选择要发放的店铺')
        return false
      }
      Dialog.confirm({
        title: '提示',
        message: '确定要发放吗?',
      })
      .then(() => {
        if (this.couponInfo.benefitBatchType == 10) {
          const params = {
            request: {
              couponBatchId: this.couponInfo.benefitBatchId,
              channelSourceType: 0,
              issuanceType: 10,
              receiverUserType: 20,
              issueCount: this.grantNum,
              receiverStoreIds: this.checkList,
            }
          }
          issueCouponToStoreList(params)
            .then((res) => {
              // console.log(res)
              if (res.errorCode == 0) {
                Toast('发放成功')
                this.grantNum = ''
                this.checkList = []
                this.totalNum = 0
                this.usable = 0
                this.couponInfo = {}
                // this.$router.back(0)
                this.show = false
                this.$emit('refresh')
              }
            })
            .catch(() => {
              // this.$message.info('取消设置!');
            })
        } else {
          const params = {
            request: {
              benefitPackageBatchIds: [this.couponInfo.benefitBatchId],
              channelSourceType: 0,
              issuanceType: 10,
              receiverUserType: 20,
              benefitPackageStatus: 18,
              receiveIds: this.checkList,
            }
          }
          addBenefitPackageList(params)
            .then((res) => {
              // console.log(res)
              if (res.errorCode == 0) {
                Toast('发放成功')
                this.grantNum = ''
                this.checkList = []
                this.totalNum = 0
                this.usable = 0
                this.couponInfo = {}
                // this.$router.back(0)
                this.show = false
                this.$emit('refresh')
              }
            })
            .catch(() => {
              // this.$message.info('取消设置!');
            })
        }
      })
    },

    // 获取店铺列表
    async getStoreList () {
      try {
        const params = {
          request: {
            dto: {
              ...this.queryParams
            }
          }
        }
        const res = await getStoreList(params)
        // console.log('店铺列表', res)
        if (res.errorCode === 0) {
          if (res.response.records.length) {
            this.storeList = this.queryParams.pageNum > 1 ? [...this.storeList, ...res.response.records] : res.response.records
            // if (this.checkAll) {
            //   this.checkList = this.storeList.map(item => item.storeId)
            // }
            // this.checkAll = false
            const list = this.storeList.map(item => item.storeId)
            const checkedCount = this.checkList.filter(item => list.includes(item)).length
            this.checkAll = checkedCount === this.storeList.length
          }
          else {
            this.storeList = this.queryParams.pageNum > 1 ? this.storeList : res.response.records
            this.checkAll = false
          }
          if (res.response.records.length < this.queryParams.pageSize) {
            this.finished = true
            this.loading = true
          } else {
            this.finished = false
            this.loading = false
          }
        }
      } catch (error) {
        console.error(error)
      }
    },

    // 获取剧本列表
    async getScriptList () {
      try {
        const params = {
          request: {
            dto: {
            }
          }
        }
        const res = await getApplyScriptList(params)
        console.log('剧本列表', res)
        if (res.errorCode === 0) {
          this.scriptList = res.response.map(item => {
            return {
              id: item.scriptId,
              ...item
            }
          })
        }
      } catch (error) {
        console.error(error)
      }
    },

    // 获取批次列表
    async getBatchList () {
      try {
        const params = {
          request: {
            pageNum: 1,
            pageSize: 100,
            issuanceType: 10,
            isGrant: 0,
            batchStatus: 10
          }
        }
        const res = await selectCouponPage(params)
        console.log('批次列表', res)
        if (res.errorCode === 0) {
          this.batchList = res.response.records
        }
      } catch (error) {
        console.error(error)
      }
    },
  }
};
</script>

<style lang="less">
.CouponGrant {
  background: #F6F6F6;
  height: calc(100vh - var(--navHeight));
  .couponItem{
    width: 100%;
    position: relative;
    background: #fff;
    padding: 20px 15px 8px 15px;
    /* border: 1rpx solid #D3D3D3; */
    border-radius: 8px;
    // box-shadow: 0px 2px 6px rgba(0, 0, 0, 0.10);
  }

  .grant_coupon_tag {
    padding: 2px 6px;
    position: absolute;
    top: 0;
    left: 0;
    flex-shrink: 0;
    border-top-left-radius: 10px;
    border-bottom-right-radius: 10px;
    color: #fff;
    font-size: 12px;
    font-style: italic;
    font-weight: 700;
  }
  .package_bg {
    background: linear-gradient(99deg, #F9B745 5.55%, #FFE86D 88.96%);
  }
  .grant_coupon_bg {
    background: linear-gradient(105deg, #FC792A 14.02%, #FF3FA2 60.46%);
  }

  .grant_coupon_header {
    padding-bottom: 10px;
    box-sizing: border-box;
  }

  .grant_coupon_title {
    color: #131419;
    font-size: 16px;
    font-weight: 600;
  }
  .grant_coupon_time {
    color: #5B554C;
    font-size: 12px;
    margin-top: 4px;
  }
  .studio_icon {
    width: 50px;
    height: 50px;
    display: block;
    margin-right: 12px;
  }
  .studio-tag {
    margin-top: 4px;
    display: inline-flex;
    border: 1rpx solid #D4AB19;
    border-radius: 16px;
    color: #D4AB19;
    padding: 6px 8px;
    font-size: 12px;
  }
  .studio-tag-icon {
    width: 12px;
    height: 12px;
    display: block;
    margin-right: 4px;
  }
}
.grant_header {
  .van-cell {
    background: #F7F8FA;
    border-radius: 4px;
    padding: 4px 12px;
  }
}
.grant_content {
  .van-checkbox {
    width: 100%;
    display: flex;
  }
  .van-checkbox__label {
    padding-left: 8px;
    flex: 1;
    overflow: hidden;
  }
}
.grant_footer {
  .van-checkbox__label {
    font-size: 14px;
    margin-left: 6px;
    font-weight: bold;
  }
  .van-cell {
    border-radius: 8px;
  }
}

.bkra_tlr_8 {
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

.bkb_f3 {
  border-bottom: 1px solid #F3F3F3;
}

.dx_11 {
  font-size: 11px;
}

.color_red {
  color: #FF6969;
  line-height: 1;
}
.color_c2 {
  color: #C26448;
}

.mt_6 {
  margin-top: 6px;
}

.lh_12 {
  line-height: 12px;
}

.pdr_15 {
  padding-right: 15px;
}
.pad_8_16 {
  padding: 8px 16px;
}
.pad_12 {
  padding: 12px;
}
.plr_12 {
  padding: 0 12px;
}
.pdl_12 {
  padding-left: 12px;
}

.w_30 {
  width: 30px;
}

.grant_btn {
  width: 70%;
  height: 48px;
  background: #D1FB71;
  font-size: 16px;
  font-weight: bold;
  border-radius: 12px;
}

</style>
